package homework.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Util {
	
	static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { } }
	
	private static final String url = "jdbc:mysql://localhost/db";
	
	private static final String user = "root", password = "root";
	
	public static String[] asSqlArgs(String ... args) {
		
		return args;
	}
	
	public static String[] emptySqlArgs() {
		
		return asSqlArgs();
	}
	
	private static void closeStatement(Statement statement) {
		
		try { if(statement != null) statement.close(); } catch(Exception e) { }
	}
	
	private static void closeConnection(Connection connection) {
		
		try { if(connection != null) connection.close(); } catch(Exception e) { }
	}
	
	public static void execute(String sql, String[] args, SqlConsumer consumer) {
		
		Connection connection = null;
		
		PreparedStatement statement = null;
		
		try {
			
			connection = DriverManager.getConnection(url, user, password);
			
			statement = connection.prepareStatement(sql, args);
			
			for(int i = 1; i <= args.length; ++i) statement.setString(i, args[i - 1]);
			
			consumer.accept(statement);
					
		} catch(Exception e) { e.printStackTrace(); }
		
		closeStatement(statement);
		
		closeConnection(connection);
	}
	
	public static void query(String sql, String[] args, SqlResultSetConsumer consumer) {
		
		Connection connection = null;
		
		PreparedStatement statement = null;
		
		try {
			
			connection = DriverManager.getConnection(url, user, password);
			
			statement = connection.prepareStatement(sql, args);
			
			for(int i = 1; i <= args.length; ++i) statement.setString(i, args[i - 1]);
			
			ResultSet set = statement.executeQuery();
			
			consumer.accept(set);
					
		} catch(Exception e) { e.printStackTrace(); }
		
		closeStatement(statement);
		
		closeConnection(connection);	 	
	}
	
	@FunctionalInterface public interface SqlConsumer {
		void accept(PreparedStatement statement) throws Exception;
	}
	
	@FunctionalInterface public interface SqlResultSetConsumer {
		void accept(ResultSet statement) throws Exception;
	}
}
